package com.codegravity.mobile.expensms;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.appwidget.AppWidgetManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.telephony.SmsMessage;

public class SMSReceiver extends BroadcastReceiver {
	static SharedPreferences myPrefs;
	private static final String ACTION = "android.provider.Telephony.SMS_RECEIVED";
	static String s_number, s_debstr, s_decimal;

	@Override
	public void onReceive(Context context, Intent intent) {
		System.out.println("ACtion  " + intent.getAction());
		if (!intent.getAction().equals(ACTION)) {
			return;
		}
		// ---get the SMS message passed in---
		Bundle bundle = intent.getExtras();
		SmsMessage[] msgs = null;
		if (bundle != null) {
			// ---retrieve the SMS message received---
			Object[] pdus = (Object[]) bundle.get("pdus");
			msgs = new SmsMessage[pdus.length];
			String msg;
			for (int i = 0; i < msgs.length; i++) {
				msgs[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
				msg = msgs[i].getMessageBody().toString();
				myPrefs = context.getSharedPreferences("SMSExpense",
						Context.MODE_WORLD_READABLE);
				s_number = myPrefs.getString("keynum", "");
				s_decimal = myPrefs.getString("keydec", "");

				if (s_number.equals(msgs[i].getOriginatingAddress())) {
					s_debstr = myPrefs.getString("keystr", "");
					int idx1 = msg.indexOf(s_debstr);
					if (idx1 == -1)
						continue;
					int idx2 = msg.indexOf("\n", idx1);
					if (idx2 == -1)
						idx2 = msg.length();
					Pattern MY_PATTERN = Pattern.compile("[0-9|" + s_decimal
							+ "]+");
					Matcher m = MY_PATTERN.matcher(msg.substring(idx1, idx2));
					long date = 0;
					float amount = 0;
					while (m.find()) {
						System.out.println("Amount  " + m.group());
						amount = Float.parseFloat(m.group()
								.replaceAll(",", "."));
						date = msgs[i].getTimestampMillis();

						recordEntry(context, date, amount);

						triggerGraph(context);
						break;
					}
				}
			}
		}
	}

	private void recordEntry(Context context, long date, float amount) {
		ExpenseDataBase db = new ExpenseDataBase(
				context.getApplicationContext());
		db.open();
		db.createAlert(ExpenseDataBase.EXPENSE_TABLE,
				ExpenseDataBase.EXPENSE_INT, new String[] { "" + amount,
						"" + date });
		db.close();
	}

	private void triggerGraph(Context context) {
		/*
		 * AppWidgetManager appWidgetManager = AppWidgetManager
		 * .getInstance(context); RemoteViews remoteViews = new
		 * RemoteViews(context.getPackageName(), R.layout.widget_layout);
		 * ComponentName thisWidget = new ComponentName(context,
		 * SMSExpenseAppWidgetProvider.class);
		 * appWidgetManager.updateAppWidget(thisWidget, remoteViews);
		 */
		SharedPreferences myPrefs = context.getSharedPreferences("SMSExpense",
				Context.MODE_WORLD_READABLE);

		Intent intent = new Intent(context, SMSExpenseAppWidgetProvider.class);
		intent.setAction("android.appwidget.action.APPWIDGET_UPDATE");
		// Use an array and EXTRA_APPWIDGET_IDS instead of
		// AppWidgetManager.EXTRA_APPWIDGET_ID,
		// since it seems the onUpdate() is only fired on that:
		int[] ids = { myPrefs.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID,
				AppWidgetManager.INVALID_APPWIDGET_ID) };
		intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, ids);
		context.sendBroadcast(intent);

		Intent intent1 = new Intent(context,
				com.codegravity.mobile.expensms.ChartsGallery.class);
		intent1.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		intent1.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		context.startActivity(intent1);
	}
}